// 优化前的流程：
// 用户输入url->页面dns解析->解析html->其他资源的dns解析（同步，会阻塞解析html）->解析html->其他资源的dns解析（同步，会阻塞解析html）
// <script src="https://assets.cnblogs.com/scripts/jquery-3.3.1.min.js"></script>
// <img src="https://i0.hdslb.com/bfs/face/9858ececfd5f73e21fa7031043f2779fd23a820a.jpg@120w_120h_1c" alt="" loading="lazy" onload="" onerror="typeof window.imgOnError === 'function' &amp;&amp; window.imgOnError(this)">

// 优化后：
// 用户输入url->页面dns解析->提前异步解析DNS->解析html
// //用meta信息来告知浏览器, 当前页面要做DNS预解析
// <meta http-equiv="x-dns-prefetch-control" content="on"></meta>
// <link rel="dns-prefetch" href="https://assets.cnblogs.com">
// <link rel="dns-prefetch" href="https://i0.hdslb.com">

const fs = require('fs');
const path = require('path');
const {parse} = require('node-html-parser');
const {glob} = require('glob');
const {urlRegex} = require('url-regex');
const { strict } = require('assert');


// 获取外部链接的正则表达式
const urlPattern = /(https?:\/\/[^/]*)/i;
const urls = new Set();

// 遍历dist目录中的所有HTML、js、css文件
async function searchDomin(){
    const files = await glob('dist/**/*.{html,css,js}');
    for(const file of files){
        const source = fs.readFileSync(file,'utf-8');
        const matches = source.match(urlRegex({strict:true}))
        if(matches){
            matches.forEach((url)=>{
                const match = url.match(urlPattern);
                if(match && match[1]){
                    urls.add(match[1]);
                }
            });
        }
    }
}


async function insertLinks(){
    const files = await glob('dist/**/*.html');
    const links = [...urls]
    .map((url)=>`<link rel="dns-prefetch" href="${url}" />`)
    .join('\n');

    for(const file of files){
        const html = fs.readFileSync(file,'utf-8');
        const root = parse(html);
        const head = root.querySelector('head');
        head.insertAdjacentHTML('afterbegin',links);
        fs.writeFileSync(file,root.toString());
    }
}

async function main(){
    await searchDomin();
    // 在<head>标签中添加预取链接
    await insertLinks();
}

main();
// 在打包后，执行
// vite build && node ./scripts/dns-prefetch.js


